package com.book.service.impl;

import com.book.dao.BorrowMapper;
import com.book.entity.Borrow;
import com.book.service.BorrowService;
import com.book.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.List;

public class BorrowServiceImpl implements BorrowService {
    @Override
    public List<Borrow> getBorrowList() {
        // 获取借阅列表
        try (SqlSession sqlSession = MybatisUtil.getSession()) {
            BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            List<Borrow> borrows = borrowMapper.getBorrowList();
            // mapper操作数据库必须放在try-resource方法体内，因为sql会话只在方法体内有效，方法体内代码执行完就会关闭sql会话
            // 如果在try-resource方法体外操作数据库，会收到Executor was closed 报错
            return borrows;
        }

    }

    @Override
    public Integer countBorrow() {
        // 统计借阅数量
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            return borrowMapper.countBorrow();
        }
    }

    @Override
    public Integer insertBorrow(LocalDateTime localDateTime, Integer bookId, Integer studentId) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            borrowMapper.insertBorrow(localDateTime, bookId, studentId);
            return 1;
        }
    }

    @Override
    public Integer deleteBorrowById(Integer id) {
        try(SqlSession sqlSession = MybatisUtil.getSession()){
            BorrowMapper borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            borrowMapper.deleteBorrowById(id);
            return 1;
        }
    }
}
